﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Nuane.Posterous
{
	/// <summary>
	/// Represents a new posterous comment.
	/// </summary>
	public class PosterousNewComment : IPosterousData
	{
		//URL
		//    * http://posterous.com/api/newcomment
		//Fields
		//    * "post_id" - The post id to comment on
		//    * "comment" - The comment body
		//    * "name" - Optional. The name to use
		//    * "email" - Optional. The email address to use
		//    * "date" - Optional. In GMT. Any parsable format. Cannot be in the future.

		/// <summary>
		/// Gets or sets the body of this comment.
		/// </summary>
		/// <value>Comment body.</value>
		public string Body { get; set; }

		/// <summary>
		/// Gets or sets the UTC datetime of this comment.
		/// </summary>
		/// <value>Comment UTC datetime.</value>
		public DateTime? Date { get; set; }

		/// <summary>
		/// Gets or sets the comment author. This can only be used by authenticated users posting on their own sites.
		/// </summary>
		/// <value>Comment author.</value>
		public string Author { get; set; }

		/// <summary>
		/// Gets the comment author e-mail. This can only be used by authenticated users posting on their own sites.
		/// </summary>
		/// <value>Comment author e-mail.</value>
		public string AuthorMailAddress { get; set; }

		/// <summary>
		/// Creates a new comment with the specified body. Use <see cref="PosterousSession.AddComment"/> or <see cref="PosterousPost.AddComment"/>to publish this comment.
		/// </summary>
		/// <param name="body">Comment text.</param>
		public PosterousNewComment(string body)
		{
			Body = body;
		}

		byte[] IPosterousData.ToData(string splitter, string source, Uri sourceLink)
		{
			MemoryStream buffer = new MemoryStream();

			Helper.AppendField(buffer, splitter, "comment", (Body != null) ? Body : "", Encoding.UTF8);

			if (!string.IsNullOrEmpty(Author))
				Helper.AppendField(buffer, splitter, "name", Author, Encoding.UTF8);

			if (!string.IsNullOrEmpty(AuthorMailAddress))
				Helper.AppendField(buffer, splitter, "email", AuthorMailAddress, Encoding.UTF8);

			if (Date != null)
			{
				DateTime date = DateTime.Now;
				if (Date.Value < date)
					date = Date.Value;
				Helper.AppendField(buffer, splitter, "date", Helper.ToString(date), Encoding.ASCII);
			}

			Helper.AppendEnd(buffer, splitter);

			return buffer.ToArray();
		}

	}
}
